import 'package:flutter/material.dart';
import 'package:flutter_1800/pages/goods/ConfirmOrder.dart';
import 'package:flutter_1800/pages/widgets/LeftSlideActions.dart';
import 'package:flutter_1800/pages/widgets/MyNetImage.dart';
import 'package:flutter_1800/pages/widgets/MyText.dart';
import 'package:flutter_1800/service/api_service.dart';
import 'package:flutter_1800/tools/AppUtil.dart';
import 'package:flutter_1800/tools/config.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';

class CarTabViewPage extends StatefulWidget {
  const CarTabViewPage({Key? key}) : super(key: key);

  @override
  _CarTabViewPageState createState() => _CarTabViewPageState();
}

class _CarTabViewPageState extends State<CarTabViewPage> {
  var list = [];
  final RefreshController _refreshController =
      RefreshController(initialRefresh: false);

  bool selectedAll = false;
  List goodsList = [];

  @override
  void initState() {
    super.initState();
    queryData();
    queryGoodsData();
  }

  ///see AutomaticKeepAliveClientMixin

  void addCart(Map item, int num) {
    int n = item["num"] + num;
    if (n < 1) {
      return;
    }
    ApiService.addCart(
      item["goodsid"],
      AppUtil.user!.id,
      1,
      item["specid"],
      item["specname"],
      item["specprice"].toDouble(),
      item["specunit"],
    ).then((value) {
      queryData();
    });
  }

  void removeItem(Map item) {}

  void queryData() {
    ApiService.cartList().then((value) {
      setState(() {
        list = value;
        for (var item in list) {
          item["selected"] = false;
        }
        _refreshController.refreshCompleted();
      });
    });
  }

  void queryGoodsData() {
    ApiService.queryGoods(1).then((value) {
      setState(() {
        goodsList = value;
      });
    });
  }

  void selectAll() {
    selectedAll = !selectedAll;
    for (var item in list) {
      item["selected"] = selectedAll;
    }
    setState(() {});
  }

  void submit() async {
    List l = [];
    for (int i = 0; i < list.length; i++) {
      Map item = list[i];
      if (item["selected"]) {
        l.add(item);
      }
    }
    ApiService.preOrder({
      "goodsList": l,
      "userid": AppUtil.user!.id,
    }).then((value) {
      AppUtil.getTo(ConfirmOrder(value));
    });

    //
  }

  @override
  Widget build(BuildContext context) {
    double totalPrice = 0;
    int length = 0;
    for (int i = 0; i < list.length; i++) {
      Map item = list[i];
      if (item["selected"]) {
        length++;
        totalPrice = totalPrice + (item["price"] ?? 0) * item["num"];
      }
    }
    return Scaffold(
      appBar: AppBar(
        shadowColor: Colors.transparent,
        centerTitle: true,
        elevation: 0.0,
        toolbarHeight: 40,
        title: MyText(
          "购物车",
          weight: FontWeight.bold,
        ),
      ),
      body: Container(
          decoration: const BoxDecoration(color: AppConfig.grayBgColor),
          child: Column(
            children: [
              Expanded(
                  child: SingleChildScrollView(
                child: Column(
                  children: [
                    const SizedBox(height: 15),
                    Container(
                      padding: AppUtil.getCommonPadding(),
                      color: Colors.white,
                      child: Row(
                        children: [
                          GestureDetector(
                              behavior: HitTestBehavior.opaque,
                              onTap: () {
                                selectAll();
                              },
                              child: selectedAll
                                  ? Image.asset(
                                      "images/mall/checked.png",
                                      width: 20,
                                      height: 20,
                                    )
                                  : Image.asset(
                                      "images/mall/unchecked.png",
                                      width: 20,
                                      height: 20,
                                    )),
                          const SizedBox(width: 10),
                          Container(
                            padding: const EdgeInsets.all(3),
                            decoration: const BoxDecoration(
                                color: AppConfig.themeDeepColor),
                            child: MyText(
                              "商品列表",
                              color: Colors.white,
                              fontSize: 13,
                            ),
                          ),
                          const SizedBox(width: 10),
                        ],
                      ),
                    ),
                    ...list.map((item) {
                      return LeftSlideActions(
                          actionsWidth: 40,
                          actions: [
                            GestureDetector(
                              behavior: HitTestBehavior.opaque,
                              onTap: () {
                                removeItem(item);
                              },
                              child: Container(
                                width: 40,
                                alignment: Alignment.center,
                                decoration: const BoxDecoration(
                                    color: Color(0xffF42648)),
                                child: MyText(
                                  "删除",
                                  color: Colors.white,
                                ),
                              ),
                            )
                          ],
                          child: GestureDetector(
                              onTap: () {},
                              behavior: HitTestBehavior.opaque,
                              child: Container(
                                padding: EdgeInsets.fromLTRB(
                                    AppUtil.getPadding(),
                                    10,
                                    AppUtil.getPadding(),
                                    10),
                                decoration: const BoxDecoration(
                                  color: Colors.white,
                                ),
                                child: Row(
                                  children: [
                                    GestureDetector(
                                      behavior: HitTestBehavior.opaque,
                                      onTap: () {
                                        setState(() {
                                          item["selected"] = !item["selected"];
                                        });
                                      },
                                      child: item["selected"] == true
                                          ? Image.asset(
                                              "images/mall/checked.png",
                                              width: 20,
                                              height: 20,
                                            )
                                          : Image.asset(
                                              "images/mall/unchecked.png",
                                              width: 20,
                                              height: 20,
                                            ),
                                    ),
                                    const SizedBox(
                                      width: 5,
                                    ),
                                    ClipRRect(
                                      child: MyNetImage(
                                        url: item["image"],
                                        width: 90,
                                        height: 90,
                                        fit: BoxFit.cover,
                                      ),
                                      borderRadius: BorderRadius.circular(10),
                                    ),
                                    const SizedBox(width: 10),
                                    Expanded(
                                        child: SizedBox(
                                      height: 90,
                                      child: Column(
                                        crossAxisAlignment:
                                            CrossAxisAlignment.start,
                                        mainAxisAlignment:
                                            MainAxisAlignment.spaceBetween,
                                        children: [
                                          MyText(
                                            item["title"],
                                            fontSize: 15,
                                            maxLines: 2,
                                          ),
                                          Row(
                                            mainAxisAlignment:
                                                MainAxisAlignment.spaceBetween,
                                            children: [
                                              MyText(
                                                "¥" +
                                                    (item["price"].toString()),
                                                color: const Color(0xffF44453),
                                                fontSize: 16,
                                                weight: FontWeight.bold,
                                              ),
                                              Row(
                                                mainAxisAlignment:
                                                    MainAxisAlignment
                                                        .spaceBetween,
                                                children: [
                                                  Container(
                                                    child: Row(
                                                      children: [
                                                        GestureDetector(
                                                          onTap: () {
                                                            addCart(item, -1);
                                                          },
                                                          child: Container(
                                                            child: MyText(
                                                              "-",
                                                              fontSize: 20,
                                                            ),
                                                            padding:
                                                                const EdgeInsets
                                                                    .fromLTRB(
                                                                    12,
                                                                    8,
                                                                    12,
                                                                    8),
                                                            decoration:
                                                                const BoxDecoration(
                                                              borderRadius: BorderRadius.only(
                                                                  bottomLeft: Radius
                                                                      .circular(
                                                                          20),
                                                                  topLeft: Radius
                                                                      .circular(
                                                                          20)),
                                                              // border: Border.all(
                                                              //     color: const Color(
                                                              //         0xffD9D9D9))
                                                            ),
                                                          ),
                                                        ),
                                                        Container(
                                                          child: MyText(
                                                              item["num"]
                                                                  .toString()),
                                                          padding: AppUtil
                                                              .getEdgeInsets(
                                                                  horizontal:
                                                                      14,
                                                                  vertically:
                                                                      5),
                                                          decoration: BoxDecoration(
                                                              borderRadius:
                                                                  BorderRadius
                                                                      .circular(
                                                                          5),
                                                              border: Border.all(
                                                                  color: const Color(
                                                                      0xffD9D9D9))),
                                                        ),
                                                        GestureDetector(
                                                            onTap: () {
                                                              addCart(item, 1);
                                                            },
                                                            child: Container(
                                                              child: MyText(
                                                                "+",
                                                                fontSize: 20,
                                                              ),
                                                              padding:
                                                                  const EdgeInsets
                                                                      .fromLTRB(
                                                                      12,
                                                                      8,
                                                                      12,
                                                                      8),
                                                              decoration:
                                                                  const BoxDecoration(
                                                                borderRadius: BorderRadius.only(
                                                                    topRight: Radius
                                                                        .circular(
                                                                            20),
                                                                    bottomRight:
                                                                        Radius.circular(
                                                                            20)),
                                                                // border: Border.all(
                                                                //     color:
                                                                //         const Color(0xffD9D9D9))
                                                              ),
                                                            )),
                                                      ],
                                                    ),
                                                  )
                                                ],
                                              )
                                            ],
                                          )
                                        ],
                                      ),
                                    )),
                                  ],
                                ),
                              )));
                      // }

                      // return FrameSeparateWidget(
                      //     index: index, placeHolder: Container(), child: widget);
                    }),
                    const SizedBox(height: 20),
                  ],
                ),
              )),
              Container(
                padding: EdgeInsets.fromLTRB(
                    AppUtil.getPadding(), 20, AppUtil.getPadding(), 20),
                color: Colors.white,
                child: Row(
                  children: [
                    GestureDetector(
                        behavior: HitTestBehavior.opaque,
                        onTap: () {
                          selectAll();
                        },
                        child: selectedAll
                            ? Image.asset(
                                "images/mall/checked.png",
                                width: 20,
                                height: 20,
                              )
                            : Image.asset(
                                "images/mall/unchecked.png",
                                width: 20,
                                height: 20,
                              )),
                    const SizedBox(
                      width: 10,
                    ),
                    MyText("全选"),
                    const SizedBox(width: 10),
                    Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Row(
                          children: [
                            MyText("合计:"),
                            MyText(
                              "¥" + totalPrice.toString(),
                              fontSize: 18,
                              weight: FontWeight.bold,
                            ),
                          ],
                        ),
                      ],
                    ),
                    const Spacer(),
                    InkWell(
                      onTap: () {
                        if (length == 0) {
                          EasyLoading.showError("请选择商品");
                          return;
                        }
                        submit();
                      },
                      child: Container(
                          width: 100,
                          padding: const EdgeInsets.all(10),
                          decoration: BoxDecoration(
                              borderRadius: BorderRadius.circular(5),
                              color: AppConfig.themeDeepColor),
                          child: MyText(
                            "去结算(" + length.toString() + ")",
                            color: Colors.white,
                          )),
                    ),
                  ],
                ),
              )
            ],
          )),
    );
  }
}
